package cn.edu.ctbu.datajpa01.service;

import cn.edu.ctbu.datajpa01.domain.Student;
import cn.edu.ctbu.datajpa01.repository.StudentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class StudentService{
    @Autowired
    private StudentRepository studentRepository;
//拓展功能函数写在这里

    public List<Student> findAll(){
        return studentRepository.findAll();
    }
    public Page<Student> findAll(Pageable pageable){
        return studentRepository.findAll(pageable);
    }

    /*
    *按Id进行查询
    * id 主键 整数
    *
     */

    public Student findById(Integer id){
        return studentRepository.findById(id).orElse(null);//orElse如果找到就返回，找不到就为空
    }

    public Student findByNo(Long no){
        return studentRepository.findByNo(no);//orElse如果找到就返回，找不到就为空
    }

    /*
     *按名字进行查询 Like
     * id 主键 整数
     *
     */


    public List<Student> findByName(String name){
        return studentRepository.findByNameLike(name);//orElse如果找到就返回，找不到就为空
    }

    /**
     * 按名字和密码进行查询
     * @param name
     * @param password
     * @return
     */
    public List<Student> findByNameAndPassword(String name,String password){
        return studentRepository.findByNameAndPassword( name, password);
    }

    /**
     * 将学生对象添加到表中
     *
     * @param student
     * @return
     */
    public void Insert(Student student){
        studentRepository.save(student);

    }

    /**
     * 改变表中学生对象的属性
     * @param student
     */
    public void upData(Student student){//对应视频23：50
        studentRepository.save(student);
    }

    /**
     * 删除表中学生对象的属性
     * @param id
     */
    public void delete(Integer id){studentRepository.deleteById(id);}

    public void save(Student student) {studentRepository.save(student);
    }

    public Student insert(Student student) {
        studentRepository.save(student);
        return student;
    }

    /**
     * 按名字和密码进行验证
     * @param name
     * @param password
     * @return
     */
    public Boolean validByNameAndPassword(String name,String password) throws Exception {
        List<Student> students=studentRepository.findByNameAndPassword(name,password);
        if ( students.size()>0) {
            //找到用户
            return true;
        }else {throw new Exception("出错了，无效的用户名和密码呢！！！");}

    }
}
